<!--
  AI出题与对话主页面
  支持用户登录、题目生成、AI对话、历史记录等功能
-->
<template>
  <MainLayout>
    <template #user-bar>
      <div v-if="userStore.userInfo" class="user-bar">
        <span class="username">{{ userStore.userInfo.username }}</span>
        <el-button type="text" @click="handleLogout">退出登录</el-button>
      </div>
      <div v-else class="user-bar">
        <el-button type="primary" @click="showLoginDialog">登录</el-button>
      </div>
    </template>
    <div v-if="!userStore.userInfo" class="centered-container">
      <div class="greeting-row" style="display: flex; align-items: flex-end; justify-content: center; gap: 24px;">
        <span class="greeting-text">{{ getGreeting() }}，欢迎来到知学岛</span>
        <span class="greeting-sub">小岛等你答题</span>
      </div>
      <el-button type="primary" class="start-quiz-btn" style="margin-bottom:32px;" @click="startQuiz">开始答题</el-button>
      <div class="brand-slogan">知学岛 - 解锁高效学习，AI答题随叫随到！</div>
    </div>
    <div v-else>
      <div v-if="!quizStarted" class="centered-container">
        <div class="greeting-row" style="display: flex; align-items: flex-end; justify-content: center; gap: 24px;">
          <span class="greeting-text">{{ getGreeting() }}，{{ userStore.userInfo.username }}</span>
          <span class="greeting-sub">小岛等你答题</span>
        </div>
        <el-button type="primary" class="start-quiz-btn" style="margin-bottom:32px;" @click="startQuiz">开始答题</el-button>
        <div class="brand-slogan">知学岛 - 解锁高效学习，AI答题随叫随到！</div>
        <!-- 移除输入框和输入区 -->
      </div>
      <div v-else>
        <div class="chat-content-wrapper chat-content-has-inputbar">
          <div v-if="messages.length > 0" class="chat-messages-area" ref="chatBodyRef">
            <div
              v-for="(msg, idx) in messages"
              :key="idx"
              :class="['chat-bubble-row', msg.role === 'user' ? 'user-row' : 'assistant-row']"
            >
              <div :class="['chat-bubble', msg.role]" v-if="msg.role === 'user'">
                <span>{{ msg.content }}</span>
              </div>
              <div v-else class="assistant-plain">
                <template v-if="msg.loading">
                  <!-- 加载动画 -->
                  <div class="loading-bubble">
                    <span class="dot"></span>
                    <span class="dot"></span>
                    <span class="dot"></span>
                  </div>
                </template>
                <template v-else>
                  <template v-if="hasButton(msg.content)">
                    <!-- 原有按钮渲染逻辑 -->
                    <template v-for="(part, pidx) in parseAssistantContent(msg.content)" :key="pidx">
                      <template v-if="part.type === 'text'">
                        {{ part.value }}
                      </template>
                    </template>
                    <!-- 选择题选项2x2排列 -->
                    <div v-if="hasButton(msg.content) && getButtonContainerClass(msg.content)==='button-list'" class="button-list-2x2">
                      <div v-for="(row, ridx) in groupButtons(parseAssistantContent(msg.content), 2)" :key="ridx" class="button-row-2x2">
                        <el-button
                          v-for="(btn, bidx) in row"
                          :key="bidx"
                          type="primary"
                          size="small"
                          class="inline-btn grade-btn"
                          @click="handleAssistantButton(btn.value, idx, bidx)"
                        >
                          <MathText :text="btn.value" />
                        </el-button>
                      </div>
                    </div>
                    <!-- 其它区域按钮 -->
                    <div v-else-if="hasButton(msg.content)" :class="getButtonContainerClass(msg.content)">
                      <template v-for="(part, pidx) in parseAssistantContent(msg.content)" :key="'btn-'+pidx">
                        <template v-if="part.type === 'button'">
                          <el-button
                            type="primary"
                            size="small"
                            class="inline-btn grade-btn"
                            @click="handleAssistantButton(part.value, idx, pidx)"
                          >
                            <MathText :text="part.value" />
                          </el-button>
                        </template>
                      </template>
                      <!-- 知识点输入框 -->
                      <div v-if="shouldShowKnowledgeInput(msg.content)" class="knowledge-input-container">
                        <el-input
                          v-model="customKnowledge"
                          placeholder="请输入知识点，如：分数加减法、一元二次方程等"
                          class="knowledge-input"
                          size="small"
                        />
                        <el-button
                          type="success"
                          size="small"
                          @click="handleCustomKnowledge"
                          :disabled="!customKnowledge.trim()"
                          class="knowledge-submit-btn"
                        >
                          确定
                        </el-button>
                      </div>
                    </div>
                  </template>
                  <template v-else>
                    <div style="white-space: pre-line; word-break: break-all; margin-bottom: 4px;">
                      <div v-html="formatAiContent(msg.content)" />
                    </div>
                  </template>
                </template>
                <!-- 加载动画 -->
                <div v-if="loadingBubble && idx === messages.length - 1" class="loading-bubble">
                  <span class="dot"></span>
                  <span class="dot"></span>
                  <span class="dot"></span>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="empty-hint">
            <span>暂无历史消息</span>
          </div>
          <!-- 输入区迁移到主内容容器内 -->
          <div class="chat-input-bar-fixed">
            <div class="centered-input chat-input-card">
              <div class="chat-input-row" style="display: flex; align-items: center; width: 100%; height: 48px;">
                <!-- 输入框 -->
                <el-input
                  v-model="input"
                  placeholder="给 小岛 发送消息"
                  class="chat-input"
                  :maxlength="2000"
                  :autosize="{ minRows: 1, maxRows: 4 }"
                  type="textarea"
                  @keyup.enter="handleSend"
                  :disabled="!userStore.userInfo"
                  @focus="!userStore.userInfo && showLoginDialog()"
                  style="flex:1; min-width:0; align-self: stretch;"
                />
                <!-- 麦克风按钮 -->
                <button
                  class="circle-icon-btn"
                  :class="{ recording: isRecording }"
                  @click="toggleVoiceInput"
                  :disabled="!userStore.userInfo"
                  aria-label="语音输入"
                  style="margin-left:16px;"
                >
                  <!-- 极简统一风格麦克风SVG -->
                  <svg width="32" height="32" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <circle cx="20" cy="20" r="18" fill="#fff" stroke="#393e4a" stroke-width="2"/>
                    <rect x="16" y="12" width="8" height="12" rx="4" stroke="#393e4a" stroke-width="2" fill="none"/>
                    <line x1="20" y1="24" x2="20" y2="28" stroke="#393e4a" stroke-width="2"/>
                    <line x1="17" y1="28" x2="23" y2="28" stroke="#393e4a" stroke-width="2"/>
                  </svg>
                </button>
                <!-- 分隔线 -->
                <div class="input-divider"></div>
                <!-- 发送按钮 -->
                <button
                  class="circle-icon-btn"
                  @click="handleSend"
                  :disabled="!userStore.userInfo || !input.trim()"
                  aria-label="发送"
                  style="margin-left:0;"
                >
                  <svg width="32" height="32" viewBox="0 0 40 40" fill="none">
                    <circle cx="20" cy="20" r="18" fill="#f5f5f5" stroke="#393e4a" stroke-width="2"/>
                    <polyline points="20,13 20,27" fill="none" stroke="#393e4a" stroke-width="3" stroke-linecap="round"/>
                    <polyline points="13,20 20,13 27,20" fill="none" stroke="#393e4a" stroke-width="3" stroke-linecap="round"/>
                  </svg>
                </button>
              </div>
              <div class="chat-input-bottom-bar">
                <div class="chat-input-actions">
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </MainLayout>
</template>

<script setup>
import { ref, onMounted, nextTick, watch, onUnmounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElIcon } from 'element-plus'
import { ArrowUp } from '@element-plus/icons-vue'
import MainLayout from '@/layouts/MainLayout.vue'
import request from '@/utils/request'
import { useUserStore } from '@/store/user'
import { aiApi } from '@/api/ai'
import MathText from '@/components/MathText.vue'
import MarkdownText from '@/components/MarkdownText.vue'
import { useChatStore } from '@/store/chat'
import { cleanAiContent } from '@/utils/cleanAiContent'
import { v4 as uuidv4 } from 'uuid'
const chatStore = useChatStore()

const router = useRouter()
const userStore = useUserStore()
const route = useRoute()

// 当前会话的元信息
const currentSessionId = computed(() => route.query.sessionId)
const currentMeta = computed(() => chatStore.getSessionMeta(currentSessionId.value))

// 切换 sessionId 时自动恢复 grade/knowledgePoint
watch(
  [() => route.query.sessionId],
  async ([sessionId], [oldSessionId]) => {
    if (sessionId) {
      await loadHistory();
      // 恢复 grade/knowledgePoint
      const record = await aiApi.getHistory(userStore.userInfo.id, sessionId)
      if (record && record.code === 200 && record.data) {
        chatStore.setSessionMeta(sessionId, {
          grade: record.data.grade || '',
          knowledgePoint: record.data.knowledgePoint || ''
        })
      }
    }
  },
  { immediate: true }
)

// 加载历史消息，简化逻辑
const loadHistory = async () => {
  console.log('loadHistory called')
  // 新会话直接推送AI引导消息，不查历史
  if (window.sessionStorage.getItem('isNewSession') === '1') {
    window.sessionStorage.removeItem('isNewSession');
    messages.value = [{
      role: 'assistant',
      content: '你好！我是你的数学学习伙伴小岛 😊\n很高兴陪你一起探索数学的奥秘！无论遇到什么难题，都可以随时问我哦～\n请选择你的年级：\n[Button: "小学"] [Button: "初中"] [Button: "高中"]'
    }];
    quizStarted.value = true;
    return;
  }
  let userId = userStore.userInfo && userStore.userInfo.id
  const sessionId = route.query.sessionId
  if (!userId) {
    const localUser = localStorage.getItem('userInfo')
    if (localUser) {
      userStore.setUserInfo(JSON.parse(localUser))
      userId = userStore.userInfo && userStore.userInfo.id
      console.log('userId restored from localStorage', userId)
    }
  }
  console.log('loadHistory userId', userId, 'sessionId', sessionId)
  if (!userId || !sessionId) {
    console.warn('[loadHistory] userId 或 sessionId 缺失')
    return
  }
  try {
    const res = await aiApi.getHistory(userId, sessionId)
    console.log('[loadHistory] 历史接口返回:', res)
    if (res && res.code === 200 && res.data) {
      messages.value = [...JSON.parse(res.data.content || '[]')]
    } else {
      messages.value = []
      console.warn('[loadHistory] 没有历史消息')
    }
    quizStarted.value = true // 只要 sessionId 存在就切换到聊天界面
  } catch (e) {
    messages.value = []
    console.error('[loadHistory] 捕获异常:', e)
    quizStarted.value = true // 出错也切换到聊天界面，显示空
  }
}

const input = ref('')
const model = ref('r1')
const quickActions = ref([
  { label: '小白研报' },
  { label: 'AI搜索' },
  { label: '帮我写作' },
  { label: 'AI生图' },
  { label: '拍题答疑' }
])
const messages = ref([])
const loading = ref(false)
const chatBodyRef = ref(null)
const quizData = ref([])
const showLogin = ref(false)
const customKnowledge = ref('') // 新增：自定义知识点输入
const isRecording = ref(false)
let recognition = null

const quizStarted = ref(false) // 新增：是否已开始答题
const isWaitingAnswer = ref(false) // 新增：是否等待用户答题
const showHistorySidebar = ref(false) // 新增：历史记录侧边栏显示
const quizEnded = ref(false) // 新增：是否已结束本轮答题
const loadingBubble = ref(false)

const showLoginDialog = () => {
  window.dispatchEvent(new CustomEvent('show-login-dialog'))
}

const handleLogout = () => {
  userStore.logout()
  router.push('/login')
}

const resetChat = () => {
  input.value = ''
  customKnowledge.value = '' // 重置自定义知识点
  quizStarted.value = false // 重置为未开始
  messages.value = []
  quizData.value = []
  quizEnded.value = false // 重置答题结束状态
}

const initChat = async () => {
  messages.value = []
  quizData.value = []
  customKnowledge.value = '' // 重置自定义知识点
  await sendToAI()
}

// 优化保存历史的函数
async function saveHistoryIfReady() {
  const sessionId = currentSessionId.value
  const meta = chatStore.getSessionMeta(sessionId)
  if (
    userStore.userInfo &&
    sessionId &&
    meta.grade &&
    meta.knowledgePoint &&
    messages.value.length > 0
  ) {
    await aiApi.saveHistory(
      userStore.userInfo.id,
      sessionId,
      JSON.stringify(messages.value),
      meta.grade,
      meta.knowledgePoint
    );
  }
}

// 发送消息后保存
const sendToAI = async (userInput) => {
  if (userInput) {
    messages.value.push({ role: 'user', content: userInput })
  }
  loading.value = true
  loadingBubble.value = true
  // 先push一条占位assistant消息
  const aiMsg = { role: 'assistant', content: '', loading: true }
  messages.value.push(aiMsg)
  try {
    // 只发送非loading消息给后端
    const safeMessages = messages.value
      .filter(m => !m.loading)
      .map(m => ({ role: m.role, content: m.content }))
    const res = await request.post('/api/chat/guide-chat', { messages: safeMessages })
    if (res && res.code === 200) {
      // 替换最后一条assistant消息内容
      aiMsg.content = res.data
      aiMsg.loading = false
      nextTick(() => {
        if (chatBodyRef.value) {
          chatBodyRef.value.scrollTop = chatBodyRef.value.scrollHeight
        }
      })
      if (/题目：/.test(res.data) && /\[Button:/.test(res.data)) {
        quizData.value.push({ question: res.data, userAnswer: null, correct: null })
        isWaitingAnswer.value = true
      } else {
        isWaitingAnswer.value = false
      }
      // 优化：只有条件满足时才保存历史
      await saveHistoryIfReady();
    } else {
      if (res && res.statusCode === 500 && res.message && res.message.includes('Rescheduled')) {
        ElMessage.error('模型服务繁忙，请稍后重试')
      } else {
        ElMessage.error(res.message || 'AI服务异常')
      }
      return
    }
  } catch (e) {
    if (e && e.message && e.message.includes('Rescheduled')) {
      ElMessage.error('模型服务繁忙，请稍后重试')
    } else {
      ElMessage.error('AI服务异常')
    }
    return
  } finally {
    loading.value = false
    loadingBubble.value = false
  }
}

const handleSend = () => {
  if (!userStore.userInfo) {
    showLoginDialog();
    return;
  }
  if (!input.value.trim() || loading.value) return
  // 只有等待答题时才写入 quizData
  if (isWaitingAnswer.value && quizData.value.length > 0 && quizData.value[quizData.value.length - 1].userAnswer === null) {
    quizData.value[quizData.value.length - 1].userAnswer = input.value.trim()
    isWaitingAnswer.value = false // 答题后重置
  }
  sendToAI(input.value.trim())
  input.value = ''
}

// 新增：判断是否显示知识点输入框
function shouldShowKnowledgeInput(content) {
  return content.includes('你也可以输入其他知识点') || 
         content.includes('输入知识点') ||
         content.includes('自定义知识点')
}

// 新增：处理自定义知识点输入
function handleCustomKnowledge() {
  const sessionId = currentSessionId.value
  if (!customKnowledge.value.trim()) return
  chatStore.setSessionMeta(sessionId, { knowledgePoint: customKnowledge.value.trim() })
  sendToAI(customKnowledge.value.trim())
  customKnowledge.value = ''
  window.dispatchEvent(new CustomEvent('refresh-sidebar-sessions'))
  saveHistoryIfReady();
}

// 新增：解析AI回复内容为文本和按钮数组
function parseAssistantContent(content) {
  const result = [];
  const buttonRegex = /\[Button: "(.*?)"\]/g;
  let lastIndex = 0;
  let match;
  while ((match = buttonRegex.exec(content)) !== null) {
    if (match.index > lastIndex) {
      result.push({ type: 'text', value: content.slice(lastIndex, match.index) });
    }
    result.push({ type: 'button', value: match[1] });
    lastIndex = match.index + match[0].length;
  }
  if (lastIndex < content.length) {
    result.push({ type: 'text', value: content.slice(lastIndex) });
  }
  return result;
}

// 新增：按钮点击处理
function handleAssistantButton(label, msgIdx, btnIdx) {
  const sessionId = currentSessionId.value
  // 判断是否年级按钮
  if (["小学","初中","高中"].includes(label)) {
    chatStore.setSessionMeta(sessionId, { grade: label })
  }
  // 判断是否知识点按钮
  const allKnowledgePoints = [
    "函数与微积分","立体几何与解析几何","概率统计与逻辑",
    "代数与方程","几何进阶","概率与统计",
    "四则运算","分数小数","应用题"
  ];
  if (allKnowledgePoints.includes(label)) {
    chatStore.setSessionMeta(sessionId, { knowledgePoint: label })
    window.dispatchEvent(new CustomEvent('refresh-sidebar-sessions'))
  }
  input.value = label;
  handleSend();
  saveHistoryIfReady();
}

function getButtonContainerClass(content) {
  // 选择题选项纵向排列
  if (/题目：/.test(content) || /请选择答案/.test(content) || /A\./.test(content)) {
    return 'button-list'
  }
  // 年级/知识点选择横向排列
  if (/请选择.*年级/.test(content) || /请选择.*知识点/.test(content) || /你最想练习的知识点/.test(content)) {
    return 'button-row'
  }
  // 默认横向
  return 'button-row'
}

function hasButton(content) {
  return /\[Button:/.test(content)
}

function groupButtons(parts, size = 2) {
  const btns = parts.filter(p => p.type === 'button');
  const rows = [];
  for (let i = 0; i < btns.length; i += size) {
    rows.push(btns.slice(i, i + size));
  }
  return rows;
}

// 新建对话/刷新按钮逻辑
function handleNewChatOrRefresh() {
  // 只重置页面状态，不新建sessionId
  quizStarted.value = false;
  quizEnded.value = false;
  messages.value = [];
  quizData.value = [];
  customKnowledge.value = '';
  // 不做任何跳转，不请求后端
  router.push({ path: '/' });
}

// 开始答题按钮逻辑
const startQuiz = () => {
  if (!userStore.userInfo) {
    ElMessage.warning('请先登录');
    window.dispatchEvent(new CustomEvent('show-login-dialog'));
    return;
  }
  // 新增：标记新会话
  window.sessionStorage.setItem('isNewSession', '1');
  const newSessionId = uuidv4();
  chatStore.setSessionMeta(newSessionId, { grade: '', knowledgePoint: '' });
  router.push({ path: '/chat', query: { sessionId: newSessionId } });
  quizStarted.value = true;
  quizEnded.value = false;
  initChat();
}

// 结束答题或再次新建对话时
const handleEndQuizOrNewChat = async () => {
  const sessionId = currentSessionId.value;
  const meta = chatStore.getSessionMeta(sessionId);
  if (messages.value.length > 0) {
    // 只有有内容时才插入数据库
    await aiApi.createSession({
      sessionId,
      grade: meta.grade,
      knowledgePoint: meta.knowledgePoint,
      content: JSON.stringify(messages.value)
    });
  }
  window.dispatchEvent(new CustomEvent('refresh-sidebar-sessions'));
  quizStarted.value = false;
  quizEnded.value = false;
  messages.value = [];
  quizData.value = [];
  customKnowledge.value = '';
  router.push({ path: '/' });
}

onMounted(() => {
  console.log('GenerateQuestion mounted')
  // 页面加载时强制同步恢复 userInfo
  const localUser = localStorage.getItem('userInfo')
  if (localUser) {
    userStore.setUserInfo(JSON.parse(localUser))
  }
  quizStarted.value = false;

  // 软键盘适配
  if (window.visualViewport) {
    window.visualViewport.addEventListener('resize', adjustInputBarBottom);
  } else {
    window.addEventListener('resize', adjustInputBarBottom);
  }

  window.addEventListener('reset-chat', handleResetChat)
})

async function handleResetChat(e) {
  // 1. 保存当前会话内容
  if (userStore.userInfo && route.query.sessionId && messages.value.length > 0) {
    await aiApi.saveHistory(
      userStore.userInfo.id,
      route.query.sessionId,
      JSON.stringify(messages.value),
      chatStore.grade,
      chatStore.knowledgePoint
    );
  }
  // 2. 切换到新会话并重置内容
  quizStarted.value = false // 回到欢迎区
  // sessionId 不再需要重置
  resetChat();
}

function adjustInputBarBottom() {
  const el = document.querySelector('.chat-input-bar-fixed');
  if (!el) return;
  let bottom = 0;
  if (window.visualViewport) {
    // 软键盘弹出时，视口高度变小
    const diff = window.innerHeight - window.visualViewport.height - window.visualViewport.offsetTop;
    bottom = diff > 0 ? diff : 0;
  }
  el.style.bottom = bottom + 'px';
}

onUnmounted(() => {
  if (window.visualViewport) {
    window.visualViewport.removeEventListener('resize', adjustInputBarBottom);
  } else {
    window.removeEventListener('resize', adjustInputBarBottom);
  }
  window.removeEventListener('reset-chat', handleResetChat)
});

// 监听登录状态变化，自动重置聊天状态
// watch(userStore.userInfo, () => {
//   resetChat();
// });

// 聊天内容自动滚动到底部
watch(messages, () => {
  nextTick(() => {
    if (chatBodyRef.value) {
      chatBodyRef.value.scrollTop = chatBodyRef.value.scrollHeight
    }
  })
})

function toggleVoiceInput() {
  if (!('webkitSpeechRecognition' in window) && !('SpeechRecognition' in window)) {
    ElMessage.error('当前浏览器不支持语音识别')
    return
  }
  if (!recognition) {
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
    recognition = new SpeechRecognition()
    recognition.lang = 'zh-CN'
    recognition.continuous = false
    recognition.interimResults = false
    recognition.onresult = (event) => {
      if (event.results && event.results[0] && event.results[0][0]) {
        input.value += event.results[0][0].transcript
      }
    }
    recognition.onstart = () => {
      isRecording.value = true
    }
    recognition.onend = () => {
      isRecording.value = false
    }
    recognition.onerror = () => {
      isRecording.value = false
      ElMessage.error('语音识别失败，请重试')
    }
  }
  if (isRecording.value) {
    recognition.stop()
  } else {
    recognition.start()
  }
}

// 跳转到对应题目
function jumpToQuiz(idx) {
  // 查找该题目在 messages 中的索引
  const question = quizData.value[idx]?.question
  if (!question) return
  const msgIdx = messages.value.findIndex(m => m.content === question)
  if (msgIdx !== -1 && chatBodyRef.value) {
    // 找到对应消息，滚动到该位置
    const msgEls = chatBodyRef.value.querySelectorAll('.chat-bubble-row')
    if (msgEls[msgIdx]) {
      msgEls[msgIdx].scrollIntoView({ behavior: 'smooth', block: 'center' })
    }
  }
  showHistorySidebar.value = false
}

function formatQuestionContent(content) {
  // 匹配所有常见"题目"粗体写法，前后可有空格、冒号、中文冒号
  // 并将题目区整体包裹高亮
  return content.replace(/\*\*\s*题目\s*[:：]?\s*\*\*[\s\S]*?(?=\n|$)/g, match => {
    // 去除**和多余空格
    const text = match.replace(/\*\*|题目[:：]?/g, '').trim();
    return `<div class='question-area'>题目：${text}</div>`;
  });
}

function formatAnalysisContent(content) {
  // 小提示区高亮
  return content.replace(/小提示[：:]?/g, '<span class="hint-area">小提示：</span>');
}

function cleanSpecialChars(content) {
  return content
    .replace(/[①⑴❶➀➊]/g, '1.')
    .replace(/[②⑵❷➁➋]/g, '2.')
    .replace(/[③⑶❸➂➌]/g, '3.')
    .replace(/[④⑷❹➃➍]/g, '4.')
    .replace(/[⑤⑸❺➄➎]/g, '5.')
    .replace(/[⑥⑹❻➅➏]/g, '6.')
    .replace(/[⑦⑺❼➆➐]/g, '7.')
    .replace(/[⑧⑻❽➇➑]/g, '8.')
    .replace(/[⑨⑼❾➈➒]/g, '9.')
    .replace(/[⑩⑽❿➉➓]/g, '10.')
    .replace(/[⦿⦾•·●○]/g, '-')
    .replace(/⦿-R/g, 'R')
}

function getGreeting() {
  const hour = new Date().getHours();
  if (hour < 12) return '早上好';
  if (hour < 18) return '下午好';
  return '晚上好';
}

// 在<script setup>中，增加一个函数，将"题目"、"解析"、"提示"自动加粗
function autoBoldKeywords(text) {
  if (!text) return '';
  // 先替换欢迎语
  let t = text.replace('我是你的数学学习伙伴小岛', '我是你的数学学习伙伴小岛');
  // 先去掉已有的加粗
  t = t
    .replace(/\*\*\s*题目\s*\*\*/g, '题目')
    .replace(/\*\*\s*解析\s*\*\*/g, '解析')
    .replace(/\*\*\s*详细解析\s*\*\*/g, '详细解析')
    .replace(/\*\*\s*提示\s*\*\*/g, '提示')
    .replace(/\*\*\s*小提示\s*\*\*/g, '小提示');
  // 用表情替换关键词
  t = t
    .replace(/([\n\s\*]*)题目[：:]/g, '$1📝 题目：')
    .replace(/([\n\s\*]*)解析[：:]/g, '$1✨ 解析：')
    .replace(/([\n\s\*]*)详细解析[：:]/g, '$1✨ 详细解析：')
    .replace(/([\n\s\*]*)提示[：:]/g, '$1💡 提示：')
    .replace(/([\n\s\*]*)小提示[：:]/g, '$1💡 小提示：')
    .replace(/\n{2,}/g, '\n');
  return t;
}

// 年级按钮点击时同步到store
defineExpose({
  setGrade: (grade) => chatStore.setGrade(grade),
  setKnowledgePoint: (kp) => chatStore.setKnowledgePoint(kp)
})

function cleanExtraNewlines(text) {
  if (!text) return '';
  // 1. 统一所有换行符为\n
  // 2. 清理所有只包含空白字符的行（包括全角空格、Tab、回车等）
  // 3. 连续2个及以上空行合并为1个
  return text
    .replace(/\r\n|\r/g, '\n') // 统一换行符
    .replace(/(^[ \u3000\t\r\f]*$)/gm, '') // 清理全空白行
    .replace(/([ \u3000\t\r\f]*)\n/g, '\n') // 行尾空白
    .replace(/(\n[ \u3000\t]*){2,}/g, '\n\n'); // 连续空行只保留一个
}

// 新增：格式化AI内容为区块
function formatAiContent(text) {
  let t = cleanAiContent(autoBoldKeywords(text))
  // 先去除所有区块之间的换行
  t = t.replace(/(📝 题目：.*?)(\n+)(?=✨ 解析：|💡 提示：|$)/gs, '$1')
  t = t.replace(/(✨ 解析：.*?)(\n+)(?=💡 提示：|$)/gs, '$1')
  // 题目区块
  t = t.replace(/📝 题目：(.*?)(?=✨ 解析：|💡 提示：|$)/gs, '<div class="ai-block question">📝 题目：$1</div>')
  // 解析区块
  t = t.replace(/✨ 解析：(.*?)(?=💡 提示：|$)/gs, '<div class="ai-block analysis">✨ 解析：$1</div>')
  // 提示区块
  t = t.replace(/💡 提示：(.*?)(?=$)/gs, '<div class="ai-block hint">💡 提示：$1</div>')
  return t
}

</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Alibaba+PuHuiTi:wght@400;500;700&display=swap');

:root {
  --font-puhuiti: 'Alibaba PuHuiTi', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  --primary-green: #21ba45;
}

/* 用户名字体 */
.username {
  font-family: var(--font-puhuiti) !important;
  font-size: 22px !important;
  color: #222;
}
.user-bar .username, .username {
  font-family: var(--font-puhuiti) !important;
  font-size: 26px !important;
  line-height: 1.2 !important;
  color: #222;
}

/* 聊天气泡内容字体（AI和用户） */
.chat-bubble,
.assistant-plain,
.user-content,
.chat-bubble.user,
.chat-bubble.assistant {
  font-family: var(--font-puhuiti) !important;
  font-size: 20px !important;
}

/* Markdown 渲染内容字体 */
.markdown-body,
.markdown-text,
.markdown-content {
  font-family: var(--font-puhuiti) !important;
  font-size: 20px !important;
}

.chat-main-center,
.chat-content-wrapper,
.chat-messages-area,
.chat-input-bar-fixed,
.chat-input-card,
.centered-input {
  background: #fff !important;
}

/* 确保聊天区域背景统一为白色 */
.chat-body {
  background: #fff !important;
}

.chat-container {
  max-width: 900px;
  margin: 40px auto 0 auto;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 16px rgba(0,0,0,0.08);
  display: flex;
  flex-direction: column;
  height: 80vh;
}
.chat-header {
  padding: 18px 24px 10px 24px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}
.chat-title {
  font-size: 20px;
  font-weight: bold;
  color: #409eff;
  letter-spacing: 1px;
}
.chat-header .el-button {
  position: absolute;
  right: 24px;
  top: 16px;
}
.chat-body {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  background: #fff;
}
.chat-bubble-row {
  display: flex;
  margin-bottom: 12px; /* 原24px，减半，只留一行空行 */
}
.user-row {
  justify-content: flex-end;
}
.assistant-row {
  justify-content: flex-start;
}
.chat-bubble {
  max-width: 60%;
  padding: 10px 16px;
  border-radius: 16px;
  background: #f5f7fa;
  color: #333;
}
.chat-bubble.user {
  background: #eafaf1 !important;
  color: #21ba45 !important;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 16px;
}
.chat-bubble.assistant {
  background: #fff;
  color: #333;
  border-top-left-radius: 4px;
  border-bottom-left-radius: 16px;
}
.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin: 0 10px;
  background: #e6f0ff;
  object-fit: cover;
}
.user-content {
  white-space: pre-wrap;
}
/* 强制覆盖所有 el-button.inline-btn 的样式 */
:deep(.el-button.inline-btn),
:deep(.inline-btn) {
  border-radius: 24px !important;
  border: 2.5px solid #21ba45 !important;
  background: #fff !important;
  color: #21ba45 !important;
  font-family: 'Source Han Serif SC', 'Source Han Serif', 'Noto Serif SC', 'Songti SC', 'SimSun', serif !important;
  font-weight: 700 !important;
  font-size: 18px !important;
  min-width: 140px;
  height: 48px;
  margin: 0 16px 0 0;
  padding: 0 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: none !important;
  outline: none !important;
  text-align: center;
  transition: background 0.2s, color 0.2s, border 0.2s, transform 0.1s;
  cursor: pointer;
  box-sizing: border-box;
}
:deep(.el-button.inline-btn:hover),
:deep(.inline-btn:hover),
:deep(.el-button.inline-btn:focus),
:deep(.inline-btn:focus),
:deep(.el-button.inline-btn.active),
:deep(.inline-btn.active),
:deep(.el-button.inline-btn[aria-pressed="true"]),
:deep(.inline-btn[aria-pressed="true"]) {
  background: #21ba45 !important;
  color: #fff !important;
  border-color: #21ba45 !important;
}
.chat-footer {
  padding: 18px 24px 18px 24px;
  border-top: 1px solid #f0f0f0;
  background: #fff;
  display: flex;
  align-items: center;
  border-radius: 0 0 16px 16px;
  box-shadow: 0 -2px 8px rgba(0,0,0,0.03);
}
.el-input__inner {
  border: none !important;
  box-shadow: none !important;
  outline: none !important;
  border-radius: 24px !important;
  background: #fff !important;
  font-size: 16px;
}
.loading-bubble {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 4px;
}
.dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #21ba45;
  animation: blink 1.4s infinite both;
}
.dot:nth-child(2) { animation-delay: 0.2s; }
.dot:nth-child(3) { animation-delay: 0.4s; }
@keyframes blink {
  0%, 80%, 100% { opacity: 0.2; }
  40% { opacity: 1; }
}
.chat-disabled {
  pointer-events: none;
  opacity: 0.6;
  filter: grayscale(0.2);
}
.user-bar {
  display: flex;
  align-items: center;
  gap: 12px;
}
.username {
  font-weight: bold;
  color: #222;
}
.chat-footer-modern {
  width: 100%;
  box-sizing: border-box;
  margin: 0;
  border-radius: 0 0 20px 20px;
  box-shadow: none;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 16px 24px;
}
.chat-input-modern {
  flex: 1;
  border: none;
  outline: none;
  font-size: 16px;
  padding: 10px 0;
  background: transparent;
}
.send-btn-modern {
  background: none;
  border: none;
  cursor: pointer;
  margin-left: 8px;
  padding: 0;
  display: flex;
  align-items: center;
}
.send-btn-modern:disabled svg {
  opacity: 0.4;
}
.chat-main-center {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #fff;
  width: 100%;
  min-height: 100vh;
  position: relative;
}
.chat-main-center.is-empty {
  justify-content: center;
}
.chat-main,
.chat-main-center,
.chat-content-wrapper {
  height: 100vh;
  min-height: 0;
  overflow: hidden;
}
/* 聊天内容区高度自适应，底部为输入框预留空间，避免被遮挡 */
.chat-content-wrapper {
  display: flex;
  flex-direction: column;
  height: 100vh;
  min-height: 0;
  overflow: hidden !important;
  box-sizing: border-box;
}
.chat-messages-area {
  flex: 1 1 0;
  height: 0;
  min-height: 0;
  max-height: none;
  overflow-y: auto !important;
  overflow-x: hidden !important;
  width: 100%;
  max-width: 100%;
  margin: 0;
  padding-top: 32px;
  padding-bottom: 120px; /* 预留输入框高度，原16px，改为120px */
  padding-left: 24px;
  padding-right: 0 !important;
  background: #fff;
  border-radius: 24px 24px 0 0;
  box-sizing: border-box;
  word-break: break-all;
  white-space: pre-wrap;
}

.chat-input-card {
  width: 100%;
  max-width: 450px;
  margin: 0 auto 32px auto;
  border-radius: 24px;
  background: #fff;
  box-shadow: 0 4px 32px rgba(0,0,0,0.10);
  padding: 24px 24px 16px 24px;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  border: none;
  z-index: 1;
}
.chat-card {
  width: 700px;
  min-height: 350px;
  height: 350px;
  background: #fff;
  border-radius: 20px;
  box-shadow: 0 4px 24px #e6eaf1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  margin: 0 auto;
  transition: width 0.3s;
}
.chat-card.full-width {
  width: 100vw;
  min-width: 0;
  max-width: 100vw;
  border-radius: 0;
  box-shadow: none;
}
.chat-header-title {
  text-align: center;
  font-size: 22px;
  font-weight: bold;
  color: #409eff;
  padding: 24px 0 12px 0;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}
.chat-body {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  background: #fff;
}
/* 已移除中间收缩按钮相关样式 */
@media (max-width: 800px) {
  .chat-card, .chat-card.full-width {
    width: 100vw;
    min-width: unset;
    border-radius: 0;
  }
}
.chat-footer-large {
  width: 700px;
  margin: 24px auto 0 auto;
  max-width: 98vw;
}
.debug-input {
  background: #fff !important;
  border: 1px solid #e0e3e8 !important;
  min-width: 0;
  width: 100%;
  height: 40px;
  box-sizing: border-box;
  z-index: 2;
}
.chat-input-card {
  border: none !important;
  box-shadow: 0 4px 32px rgba(0,0,0,0.10); /* 恢复卡片阴影 */
  border-radius: 24px;
  background: #fff;
  /* 保持原有内边距和布局 */
}
.chat-header-row {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 24px;
}
.chat-logo {
  width: 48px;
  height: 48px;
  margin-right: 16px;
}
.chat-title {
  font-size: 32px;
  font-weight: 500;
  color: #222;
}
.chat-input-main {
  display: flex;
  align-items: flex-end;
  position: relative;
  margin-bottom: 12px;
}
.chat-input {
  border: none !important;
  box-shadow: none !important;
  outline: none !important;
  background: transparent !important;
  border-radius: 0 !important;
  font-size: 18px;
  color: #222;
  resize: none;
  min-height: 48px;
  padding: 0;
}

.el-textarea__inner {
  border: none !important;
  box-shadow: none !important;
  outline: none !important;
  background: transparent !important;
  border-radius: 0 !important;
  font-size: 18px;
  color: #222;
  resize: none;
  min-height: 48px;
  padding: 0;
}

.chat-input-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}
.send-btn {
  background: #eafaf1;
  color: #21ba45;
  border: none;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  box-shadow: 0 2px 8px rgba(64,158,255,0.08);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.2s;
}
.send-btn:active {
  background: #b6eac7;
}
.send-btn:disabled {
  background: #f0f0f0;
  color: #bbb;
}
.chat-input-toolbar {
  display: flex;
  align-items: center;
  margin-top: 12px;
  justify-content: space-between;
}
.model-select {
  min-width: 100px;
  max-width: 140px;
  width: 120px;
  text-align: left;
}
.quick-actions {
  display: flex;
  gap: 8px;
}
.quick-btn {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.04);
  color: #333;
  font-size: 14px;
  border: 1px solid #f0f0f0;
}
.send-btn-rect {
  background: #409eff;
  color: #fff;
  border-radius: 8px;
  min-width: 72px;
  height: 40px;
  font-size: 16px;
  box-shadow: 0 2px 8px rgba(64,158,255,0.08);
  margin-left: 12px;
}
.el-textarea__inner {
  border: none !important;
  box-shadow: none !important;
  outline: none !important;
  background: #f5f6fa !important;
  border-radius: 16px !important;
  font-size: 18px;
  color: #222;
  resize: none;
}
.chat-input-bottom-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 12px;
  gap: 8px;
}

/* 新增：知识点输入框样式 */
.knowledge-input-container {
  margin-top: 6px; /* 原12px，减小 */
  display: flex;
  gap: 8px;
  align-items: center;
  background: #f8f9fa;
  padding: 12px;
  border-radius: 12px;
  border: 1px solid #e9ecef;
}

.knowledge-input {
  flex: 1;
}

.knowledge-input .el-input__inner {
  border: 1px solid #d1d5db !important;
  border-radius: 8px !important;
  background: #fff !important;
  font-size: 14px;
}

.knowledge-submit-btn {
  border-radius: 8px;
  font-size: 14px;
  padding: 8px 16px;
  background: #10b981;
  border: none;
  color: #fff;
  transition: background 0.2s;
}

.knowledge-submit-btn:hover {
  background: #059669;
}

.knowledge-submit-btn:disabled {
  background: #9ca3af;
  cursor: not-allowed;
}

/* 新增：按钮纵向排列样式 */
.button-list {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px; /* 原12px，减小 */
}
.inline-btn {
  min-width: 120px;
  text-align: left;
  margin: 0;
}
.button-row {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  gap: 8px; /* 原16px，减小 */
  flex-wrap: nowrap;
  margin-top: 2px;
  margin-bottom: 0;
}

/* 新增：AI回复无气泡样式 */
.assistant-plain {
  background: none !important;
  box-shadow: none !important;
  border-radius: 0 !important;
  padding: 0 !important;
  color: #222;
  font-size: 16px;
  line-height: 1.8;
  margin-bottom: 4px; /* 原0，适当留一行空行 */
  max-width: 75%;
  text-align: left;
  word-break: break-word;
}

/* 聊天输入区美化升级 */
.chat-input-card {
  width: 100%;
  max-width: 720px;
  margin: 0 auto 32px auto;
  border-radius: 32px;
  background: #fff;
  box-shadow: 0 2px 16px rgba(0,0,0,0.06);
  border: 1.5px solid #f0f0f0;
  padding: 24px 32px 20px 32px;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  min-height: 90px;
}

.chat-input-main {
  display: flex;
  align-items: center;
  gap: 16px;
  width: 100%;
}

.input-icon-left {
  margin-right: 8px;
  color: #b0b4bc;
  font-size: 22px;
  cursor: pointer;
  transition: color 0.2s;
}
.input-icon-left:hover {
  color: #409eff;
}
.input-icon-right {
  margin-left: 12px;
  color: #b0b4bc;
  font-size: 22px;
  cursor: pointer;
  transition: color 0.2s;
}
.input-icon-right:hover {
  color: #409eff;
}

.chat-input {
  border: none !important;
  box-shadow: none !important;
  outline: none !important;
  background: #f5f6fa !important;
  border-radius: 16px !important;
  font-size: 17px;
  color: #222;
  resize: none;
  min-height: 44px;
  flex: 1;
  padding: 0 16px;
}

.el-textarea__inner {
  border: none !important;
  box-shadow: none !important;
  outline: none !important;
  background: #f5f6fa !important;
  border-radius: 16px !important;
  font-size: 17px;
  color: #222;
  min-height: 44px;
  padding: 10px 16px;
}

.chat-input-bottom-bar {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-top: 12px;
  gap: 16px;
}

.model-select {
  min-width: 110px;
  max-width: 140px;
  width: 120px;
  text-align: left;
  border-radius: 16px;
  background: #fff;
  border: none;
  box-shadow: none;
}

.inline-btn {
  border-radius: 16px !important;
  border: none !important;
  background: #fff !important;
  color: #222 !important;
  font-weight: 500;
  font-size: 15px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.04);
  transition: box-shadow 0.2s, background 0.2s;
  min-width: 90px;
  height: 36px;
  margin: 0 8px 0 0;
  padding: 0 18px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.inline-btn:hover {
  background: #f5f7fa !important;
  box-shadow: 0 2px 8px rgba(64,158,255,0.08);
}

.el-input__inner::placeholder,
.el-textarea__inner::placeholder {
  color: #b0b4bc !important;
  font-size: 15px;
}

.send-btn {
  background: #f0f0f0;
  color: #bbb;
  border: none;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  box-shadow: none;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.2s;
}
.send-btn:active {
  background: #e0e0e0;
}
.send-btn:disabled {
  background: #f0f0f0;
  color: #bbb;
}

/* 让按钮组横向排列 */
.button-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 16px;
  flex-wrap: nowrap;
}

.button-list-2x2 {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px; /* 原16px，减小 */
  margin-top: 6px; /* 原12px，减小 */
  width: 100%;
}
.button-row-2x2 {
  display: flex;
  flex-direction: row;
  gap: 8px; /* 原16px，减小 */
  width: 100%;
}
.button-row-2x2 .inline-btn {
  flex: 1 1 0;
  min-width: 0;
  justify-content: center;
  text-align: center;
}
.input-with-icon {
  position: relative;
  width: 100%;
}
.chat-input-row {
  display: flex;
  align-items: center;
  width: 100%;
  height: 44px;
}
.circle-icon-btn,
.input-divider {
  align-self: center;
}
.input-divider {
  margin: 0 10px;
}
.chat-input {
  width: 100%;
  min-width: 0;
  max-width: none;
  margin: 0;
}
.model-select {
  min-width: 140px;
  margin-bottom: 0;
}
.input-float-icon {
  font-size: 26px;
  color: #bbb;
  background: #f0f0f0;
  border-radius: 50%;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background 0.2s, color 0.2s;
  margin-bottom: 6px;
}
.input-float-icon:hover {
  background: #409eff;
  color: #fff;
}
.input-float-icon.disabled {
  pointer-events: none;
  opacity: 0.5;
}
.chat-input-capsule {
  display: flex;
  align-items: center;
  background: #fff;
  border: 1.5px solid #e5e7eb;
  border-radius: 16px;
  padding: 10px 18px;
  gap: 12px;
  box-shadow: none;
  width: 100%;
  min-height: 48px;
}
.input-left-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}
.input-main-flex {
  flex: 1;
  display: flex;
  align-items: center;
}
.capsule-input {
  width: 100%;
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
  outline: none !important;
  font-size: 16px;
  color: #222;
  --el-input-bg-color: transparent;
}
.capsule-input .el-textarea__inner {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
  outline: none !important;
  font-size: 16px;
  color: #222;
  padding: 0;
  min-height: 24px;
  resize: none;
}
.capsule-input .el-textarea__inner::placeholder {
  color: #6b7280 !important;
  font-size: 15px;
}
.input-right-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}
.icon-mic {
  color: #6b7280;
  font-size: 18px;
  cursor: pointer;
  border-radius: 8px;
  padding: 2px;
  transition: background 0.2s, color 0.2s;
}
.icon-mic:hover {
  color: #4b5563;
  background: #f3f4f6;
}
.capsule-send-btn {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #f3f4f6;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #6b7280;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.2s, color 0.2s;
  margin-left: 2px;
}
.capsule-send-btn:enabled:hover {
  background: #e5e7eb;
  color: #4b5563;
}
.capsule-send-btn:disabled {
  background: #f3f4f6;
  color: #d1d5db;
  cursor: not-allowed;
}
.assistant-plain,
.button-list,
.button-row,
.button-list-2x2 {
  padding-left: 0 !important;
  margin-left: 0 !important;
}
.chat-content-has-inputbar {
  padding-bottom: 80px; /* 与输入框高度一致或略大即可 */
}
.chat-input-bar-fixed {
  position: fixed;
  left: 240px;
  right: 0;
  bottom: 48px !important;
  width: auto;
  display: flex;
  justify-content: center;
  z-index: 100;
  pointer-events: none;
  background: transparent;
  transition: left 0.2s, bottom 0.2s;
}

@media (max-width: 900px) {
  .chat-input-bar-fixed {
    bottom: 48px !important;
  }
}
.chat-input-bar-fixed .chat-input-card {
  pointer-events: auto;
  width: 100%;
  max-width: 900px;
  margin: 0 auto;
  padding-left: 32px;
  padding-right: 32px;
  box-sizing: border-box;
}
@media (max-width: 900px) {
  .chat-input-bar-fixed {
    max-width: 100vw;
    left: 0;
    right: 0;
    /* bottom: 48px !important;  // 保持与PC端一致，如需移动可调整 */
  }
  .chat-input-bar-fixed .chat-input-card {
    max-width: 98vw !important;
    padding-left: 8px;
    padding-right: 8px;
  }
}
.chat-input-bar-fixed .chat-input-card,
.chat-content-wrapper,
.chat-messages-area {
  max-width: 1100px;
  width: 100%;
  margin: 0 auto;
}
@media (max-width: 1200px) {
  .chat-content-wrapper,
  .chat-messages-area,
  .chat-input-bar-fixed .chat-input-card,
  .chat-input-card {
    max-width: 98vw !important;
  }
}
.chat-messages-area {
  padding-left: 32px !important;
  padding-right: 32px !important;
}
@media (max-width: 800px) {
  .chat-messages-area {
    padding-left: 8px !important;
    padding-right: 8px !important;
  }
}
@media (max-width: 900px) {
  .chat-content-wrapper,
  .chat-messages-area,
  .chat-input-bar-fixed .chat-input-card,
  .chat-input-card {
    max-width: 98vw !important;
  }
}
@media (max-width: 900px) {
  .chat-content-wrapper,
  .chat-messages-area,
  .chat-input-bar-fixed .chat-input-card,
  .chat-input-card {
    max-width: 800px !important;
    width: 100%;
    margin: 0 auto;
    padding-left: 32px !important;
    padding-right: 32px !important;
  }
}
@media (max-width: 900px) {
  .chat-content-wrapper,
  .chat-messages-area,
  .chat-input-bar-fixed .chat-input-card,
  .chat-input-card {
    max-width: 98vw !important;
    padding-left: 8px !important;
    padding-right: 8px !important;
  }
}
.centered-container {
  min-height: 80vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.greeting-row {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 0;
}
.greeting-text {
  font-size: 64px;
  font-weight: bold;
  color: #222;
  text-align: center;
  margin-bottom: 6px; /* 原12px，减小 */
  letter-spacing: 2px;
  text-shadow: 0 2px 8px rgba(30,40,60,0.08);
}
.greeting-sub {
  color: #21ba45;
  font-size: 32px;
  font-weight: 500;
  letter-spacing: 1px;
  margin-top: 0;
  margin-bottom: 16px; /* 原32px，减小 */
  animation: floatText 2.2s ease-in-out infinite alternate;
  text-align: center;
  width: 100%;
  display: block;
}
@keyframes floatText {
  0% { transform: translateY(0); }
  100% { transform: translateY(-16px); }
}
.start-quiz-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 18px auto;
  font-size: 28px;
  height: 80px;
  min-width: 320px;
  border-radius: 48px;
  background: #21ba45;
  color: #fff;
  font-weight: bold;
  box-shadow: 0 8px 32px rgba(64,158,255,0.18);
  transition: transform 0.18s cubic-bezier(.4,1.2,.4,1), box-shadow 0.18s;
}
.start-quiz-btn:hover {
  transform: scale(1.08);
  box-shadow: 0 16px 48px rgba(64,158,255,0.28);
  background: #179a36;
}
.input-container {
  width: 100%;
  max-width: 900px;
  margin: 0 auto 32px auto;
  border-radius: 20px;
  background: #fff;
  box-shadow: 0 2px 16px rgba(0,0,0,0.08);
  padding: 24px 32px 20px 32px;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  border: none;
  min-height: 90px;
  box-sizing: border-box;
}
@media (max-width: 700px) {
  .input-container {
    max-width: 98vw;
    padding: 12px 6px 12px 6px;
  }
}
.input-container {
  border-radius: 18px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.06);
  padding: 24px 32px 20px 32px;
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
  border: none;
  background: #fff;
}
@media (max-width: 700px) {
  .input-container {
    width: 98vw;
    padding: 12px 6px 12px 6px;
  }
}
.chat-input-row {
  display: flex;
  align-items: center;
  width: 100%;
}
.chat-input {
  background: #232738 !important;
  color: #fff !important;
  border: none !important;
  box-shadow: none !important;
  outline: none !important;
  border-radius: 16px !important;
  font-size: 18px;
  flex: 1;
  min-height: 44px;
  padding: 0 16px;
}
.el-textarea__inner {
  background: #232738 !important;
  color: #fff !important;
  border: none !important;
  box-shadow: none !important;
  outline: none !important;
  border-radius: 16px !important;
  font-size: 18px;
  min-height: 44px;
  padding: 10px 16px;
}
.input-float-icon {
  background: #2d3144;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 12px;
  cursor: pointer;
  transition: background 0.2s;
}
.input-float-icon:hover {
  background: #409eff;
}
.input-float-icon svg {
  color: #fff;
  font-size: 22px;
}
.el-textarea__inner, .chat-input {
  min-height: 32px !important;
  font-size: 16px !important;
  background: #fff !important;
  color: #222 !important;
  border-radius: 8px !important;
}
.input-float-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-left: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}
@media (max-width: 500px) {
  .input-container {
    width: 98vw;
    padding: 6px 2px 6px 2px;
  }
}
.input-voice-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background 0.2s;
  background: #f5f5f5;
}
.input-voice-icon.recording {
  background: #e6f7ff;
}
.input-voice-icon svg {
  display: block;
}
.el-input,
.el-textarea,
.el-input__wrapper,
.el-input__inner,
.el-textarea__inner {
  border: none !important;
  box-shadow: none !important;
  outline: none !important;
  background: transparent !important;
}
.history-btn {
  width: 120px;
  margin-left: 12px;
}
.history-sidebar {
  position: fixed;
  top: 80px;
  right: 0;
  width: 320px;
  height: 80vh;
  background: #fff;
  box-shadow: -2px 0 16px rgba(0,0,0,0.08);
  border-radius: 12px 0 0 12px;
  z-index: 2000;
  padding: 24px 18px 18px 18px;
  overflow-y: auto;
  transition: right 0.2s;
}
.history-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 18px;
}
.history-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.history-item {
  background: #f5f6fa;
  border-radius: 8px;
  padding: 12px 10px;
  cursor: pointer;
  transition: background 0.2s;
}
.history-item:hover {
  background: #e6f7ff;
}
.history-q {
  font-size: 15px;
  color: #222;
  margin-bottom: 4px;
  font-weight: 500;
}
.history-a {
  font-size: 14px;
  color: #409eff;
}
.history-empty {
  color: #bbb;
  text-align: center;
  margin-top: 40px;
}
.question-label {
  font-weight: bold;
  color: #409eff;
  margin-right: 8px;
  letter-spacing: 1px;
  background: #eaf4ff;
  padding: 2px 8px;
  border-radius: 4px;
}
.hint-label {
  font-weight: bold;
  color: #ff9800;
  margin-right: 8px;
  letter-spacing: 1px;
  background: #fff7e6;
  padding: 2px 8px;
  border-radius: 4px;
}
.analysis-label {
  font-weight: bold;
  color: #21ba45;
  margin-right: 8px;
  letter-spacing: 1px;
  background: #eafaf1;
  padding: 2px 8px;
  border-radius: 4px;
}
/* 下拉菜单标题字体放大 */
.el-dropdown-menu__item {
  font-family: var(--font-puhuiti) !important;
  font-size: 18px !important;
}
.circle-icon-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: none;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  padding: 0;
  transition: background 0.2s;
}
.circle-icon-btn:active,
.circle-icon-btn:hover {
  background: #f0f7ff;
}
.circle-icon-btn svg {
  display: block;
}
.input-divider {
  width: 2px;
  height: 24px;
  background: #393e4a;
  opacity: 0.18;
  margin: 0 10px;
  border-radius: 2px;
  align-self: center;
}
.question-area {
  font-weight: bold;
  color: #21ba45;
  font-size: 18px;
  margin-bottom: 4px; /* 原8px，减小 */
  background: #eafaf1;
  border-radius: 8px;
  padding: 8px 16px;
  display: inline-block;
}
.hint-area {
  font-weight: bold;
  color: #ff9800;
  font-size: 16px;
  margin-top: 6px; /* 原12px，减小 */
  background: #fff7e6;
  border-radius: 8px;
  padding: 8px 16px;
  display: inline-block;
}
/* 强力去除输入框聚焦时的蓝色线框（Element Plus 相关） */
:deep(.el-textarea__inner:focus),
:deep(.el-input__inner:focus),
:deep(.el-textarea.is-focus .el-textarea__inner),
:deep(.el-input.is-focus .el-input__inner),
:deep(.el-textarea__inner),
:deep(.el-input__inner) {
  outline: none !important;
  box-shadow: none !important;
  border: none !important;
}
.brand-slogan {
  color: #888;
  font-size: 18px;
  text-align: center;
  margin-top: 6px; /* 原12px，减小 */
  letter-spacing: 1px;
}
/* 黑夜模式适配 */
html[data-theme='dark'] .chat-main-center,
html[data-theme='dark'] .chat-content-wrapper,
html[data-theme='dark'] .chat-messages-area,
html[data-theme='dark'] .chat-input-bar-fixed,
html[data-theme='dark'] .chat-input-card,
html[data-theme='dark'] .centered-input {
  background: #181c1f !important;
  color: #e6e6e6 !important;
}
html[data-theme='dark'] .chat-bubble {
  background: #23272a !important;
  color: #e6e6e6 !important;
}
html[data-theme='dark'] .chat-bubble.user {
  background: #263c2a !important;
  color: #21ba45 !important;
}
html[data-theme='dark'] .chat-bubble.assistant {
  background: #23272a !important;
  color: #e6e6e6 !important;
}
html[data-theme='dark'] .assistant-plain {
  color: #e6e6e6 !important;
}
html[data-theme='dark'] .inline-btn {
  background: transparent !important;
  color: #21ba45 !important;
  border: 2.5px solid #21ba45 !important;
}
html[data-theme='dark'] .inline-btn:hover,
html[data-theme='dark'] .inline-btn:focus,
html[data-theme='dark'] .inline-btn.active,
html[data-theme='dark'] .inline-btn[aria-pressed="true"] {
  background: #21ba45 !important;
  color: #fff !important;
  border-color: #21ba45 !important;
}
html[data-theme='dark'] .el-input__inner,
html[data-theme='dark'] .el-textarea__inner,
html[data-theme='dark'] .chat-input {
  background: #fff !important;
  color: #222 !important;
  border: none !important;
}
html[data-theme='dark'] .el-input__inner::placeholder,
html[data-theme='dark'] .el-textarea__inner::placeholder {
  color: #888 !important;
}
html[data-theme='dark'] .send-btn {
  background: #263c2a !important;
  color: #21ba45 !important;
}
html[data-theme='dark'] .send-btn:active {
  background: #21ba45 !important;
  color: #fff !important;
}
html[data-theme='dark'] .send-btn:disabled {
  background: #23272a !important;
  color: #888 !important;
}
html[data-theme='dark'] .knowledge-input-container {
  background: #23272a !important;
  border: 1px solid #263c2a !important;
}
html[data-theme='dark'] .knowledge-input .el-input__inner {
  background: #181c1f !important;
  color: #e6e6e6 !important;
  border: 1px solid #263c2a !important;
}
html[data-theme='dark'] .knowledge-submit-btn {
  background: #21ba45 !important;
  color: #fff !important;
}
html[data-theme='dark'] .knowledge-submit-btn:hover {
  background: #179a36 !important;
}
html[data-theme='dark'] .brand-slogan {
  color: #b6eac7 !important;
}
html[data-theme='dark'] .centered-container {
  background: #181c1f !important;
}
html[data-theme='dark'] .chat-input-card,
html[data-theme='dark'] .centered-input {
  box-shadow: 0 4px 32px rgba(0,0,0,0.10), 0 0 32px #fff2;
  border-radius: 32px;
  border: none;
}
/* 美化聊天内容区滚动条 */
.chat-messages-area::-webkit-scrollbar {
  width: 6px;
  background: transparent;
}
.chat-messages-area::-webkit-scrollbar-thumb {
  background: rgba(33,186,69,0.18);
  border-radius: 8px;
}
.chat-messages-area::-webkit-scrollbar-thumb:hover {
  background: rgba(33,186,69,0.32);
}
.chat-messages-area {
  scrollbar-width: thin;
  scrollbar-color: rgba(33,186,69,0.18) transparent;
}
/* 彻底隐藏主界面右侧滚动条，只让.chat-messages-area显示滚动条 */
html, body {
  height: 100vh;
  min-height: 0;
  overflow: hidden !important;
  overscroll-behavior: none !important;
}
#app, .main-layout, .chat-main, .chat-main-center, .chat-content-wrapper {
  height: 100vh;
  min-height: 0;
  overflow: hidden !important;
}

/* 新增：年级按钮字体加粗样式 */
.grade-btn { font-weight: bold; }

.empty-hint {
  text-align: center;
  color: #888;
  font-size: 18px;
  margin: 40px 0;
}

.ai-block.question {
  background: #f8f9fa;
  border-left: 4px solid #21ba45;
  margin-bottom: 8px;
  padding: 8px 12px;
}
.ai-block.analysis {
  background: #eaf4ff;
  border-left: 4px solid #409eff;
  margin-bottom: 8px;
  padding: 8px 12px;
}
.ai-block.hint {
  background: #fffbe6;
  border-left: 4px solid #f7b500;
  margin-bottom: 8px;
  padding: 8px 12px;
}
.ai-block.question,
.ai-block.analysis,
.ai-block.hint {
  margin-bottom: 2px;
}
.button-list-2x2, .button-list {
  margin-top: 4px !important;
}
.ai-highlight {
  display: inline-block;
  background: #fffbe6;
  color: #e91e63;
  font-weight: bold;
  font-size: 18px;
  padding: 2px 8px;
  border-radius: 6px;
  margin: 4px 0;
}
</style> 